import 'dart:async';

import 'package:get/get.dart';

import '../common/api_service.dart';
import '../common/events.dart';
import '../model/message_record_model.dart';

class MessageController extends GetxController {
  final List<MessageRecordModel> recordList = [];
  StreamSubscription? _loginStreamSub;
  int pageNo = 1;
  bool isLoading = false;
  bool isShowEmpty = false;
  bool isShowError = false;

  @override
  void onInit() {
    super.onInit();

    _loginStreamSub = eventBus.on<UserLoggedInEvent>().listen((event) {
      _getMessageRecordList();
    });

    _showLoading();
    _getMessageRecordList();
  }

  @override
  void onClose() {
    _loginStreamSub?.cancel();
    super.onClose();
  }

  void deleteChat(String pipeId) {
    ApiService().resetChat(pipeId, () {
      List<MessageRecordModel> removeList = [];
      for (var item in recordList) {
        item.pipeList.removeWhere((x) => x.id == pipeId);
        if (item.pipeList.isEmpty) {
          removeList.add(item);
        }
      }
      recordList.removeWhere((item) => removeList.contains(item));
      update();
    }, () {});
  }

  void _getMessageRecordList() {
    ApiService().getMessageRecordList(pageNo, (list) {
      recordList.clear();
      recordList.addAll(list);
      if (recordList.isEmpty) {
        _showEmpty();
      } else {
        _showContent();
      }
      update();
    }, () {
      _showError();
    });
  }

  void refreshData() {
    _getMessageRecordList();
  }

  void _showContent() {
    isShowEmpty = false;
    isLoading = false;
    isShowError = false;
    update();
  }

  void _showLoading() {
    isShowEmpty = false;
    isLoading = true;
    isShowError = false;
    update();
  }

  void _showEmpty() {
    isShowEmpty = true;
    isLoading = false;
    isShowError = false;
    update();
  }

  void _showError() {
    isShowEmpty = false;
    isLoading = false;
    isShowError = true;
    update();
  }
}